package d.util
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	import mx.containers.Box;
	import mx.controls.Alert;
	import mx.controls.Label;
	import mx.controls.SWFLoader;
	import mx.core.Application;
	import mx.managers.PopUpManager;
	
	/**
	 * A loading mask utility class.
	 * To use it, simply as this: 
	 *     Mask.show("Please wait...");
	 * or
	 *     Mask.show("Please wait...", theContainerIdYouWishToShowMask);
	 * When you're done, close it:
	 *     Mask.close();
	 */ 
	public class Mask extends Box
	{
		
		private static var maskGroup:Object = {};
		
		private var _message:String;
		
		[Bindable]
		[Embed(source="/asset/loading.swf")]
		private var LoadingMask:Class;
		
		public function Mask()
		{
			super();
			//this.direction = "horizontal";
			this.setStyle("horizontalAlign", "center");
			this.direction = "vertical";
		}
		
		 public static function show(maskId:String, message:String = null, parent:Sprite=null):Mask{
		 	
		 	var mask:Mask = new Mask();
		 	maskGroup[maskId] = mask;
		 	mask._message = message;
		 	PopUpManager.addPopUp(mask, parent||Sprite(Application.application), true);
		 	PopUpManager.centerPopUp(mask);
		 	
		 	return mask;
		 }
		 
		 
		 public static function close(maskId:String = null):void {
		 	if(maskId == null){
		 		// remove all masks
		 		for each(var m:Mask in maskGroup){
		 			PopUpManager.removePopUp(m);
		 		}
		 	} else {
		 		PopUpManager.removePopUp(maskGroup[maskId]);
		 	}
         }
		 
		override protected function createChildren():void
		{
        	super.createChildren();
        	
//			var pb:ProgressBar = new ProgressBar();
//			pb.label = _message||"Please wait...";
//			pb.indeterminate = true;
//			pb.labelPlacement= 'center';
//			pb.setStyle('barColor', uint(0xAEAEAE));
//			pb.height = 26;
			
			var loader:SWFLoader = new SWFLoader();
			loader.addEventListener(Event.COMPLETE, onCompleteFunc);
			loader.load(new LoadingMask());
			loader.height = 35;
			loader.width = 35;
			addChild(loader);
			
			var label:Label = new Label();
			label.height = 35;
			label.setStyle("fontWeight", "bold");
			label.setStyle("fontSize", 12);
			label.setStyle("fontColor", "#F2F8F3");
			label.text = _message||"Please wait...";
			
			addChild(label);
		}
		
		private function onCompleteFunc(e:Event):void{
			Alert.show(e.currentTarget.toString());
		}
	}
}